package com.donleo.security.config;

import com.donleo.security.service.impl.CustomUserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author liangd
 * date 2020-12-08 15:00
 * code 三、自定义实现类
 * .@EnableGlobalMethodSecurity 是否允许方法上设置权限
 *  prePostEnabled 方法执行前/后 默认为false
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 自定义配置步骤
     * 1、创建配置类  设置使用哪个UserDetailsService实现类
     * 2、编写实现类，返回User对象，User对象有用户名密码和操作权限
     */
    @Autowired
    private CustomUserDetailsServiceImpl userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //设置哪些路劲可以访问
                .antMatchers("/css/**", "/js/**", "/fonts/**").permitAll()
                //需要相应的角色才能访问
                .antMatchers("/users/**").hasRole("ADMIN")
                .anyRequest().authenticated()   // 任何请求都需要认证
                .and()
                .formLogin() //基于Form表单登录验证
                .and()
                .userDetailsService(userDetailsService);
    }

    /**
     * 创建passwordEncoder对象
     * @return
     */
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
